package com.na.proxy;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class ProxyServer implements Runnable {

	private int port;
	private ServerSocket server;
	private boolean running;
	private TaskExecutor executor;
	
	public ProxyServer(int port) {
		this.port = port;
		executor = new TaskExecutor();
	}
	
	public void open() {
		try {
			server = new ServerSocket(port);
			new Thread(this).start();
			Log.getDefault().info("ProxyServer started");
		} catch (IOException e) {
			Log.getDefault().error(e, "ProxyServer start fail");
			close();
		}
	}
	
	public void close() {
		running = false;
		if (server != null) {
			try {
				executor.shutdown();
				server.close();
				Log.getDefault().info("ProxyServer closed");
			} catch (IOException e) {
				Log.getDefault().error(e, "ProxyServer close error");
			}
		}
	}

	@Override
	public void run() {
		running = true;
		while (running) {
			try {
				Socket client = server.accept();
				executor.runTask(new ClientSession(client));
				Log.getDefault().info("accept: " + client);
			} catch (IOException e) {
				Log.getDefault().error(e);
			}
		}
	}
	
}
